package com.qing.picture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qing.picture.exception.BusinessException;
import com.qing.picture.exception.ErrorCode;
import com.qing.picture.exception.ThrowUtils;
import com.qing.picture.manager.sharding.DynamicShardingManager;
import com.qing.picture.mapper.SpaceMapper;
import com.qing.picture.model.dto.space.SpaceAddRequest;
import com.qing.picture.model.dto.space.SpaceEditRequest;
import com.qing.picture.model.dto.space.SpaceQueryRequest;
import com.qing.picture.model.dto.space.SpaceUpdateRequest;
import com.qing.picture.model.entity.Space;
import com.qing.picture.model.entity.SpaceUser;
import com.qing.picture.model.entity.User;
import com.qing.picture.model.enums.SpaceLevelEnum;
import com.qing.picture.model.enums.SpaceRoleEnum;
import com.qing.picture.model.enums.SpaceTypeEnum;
import com.qing.picture.model.vo.SpaceVo;
import com.qing.picture.model.vo.UserVo;
import com.qing.picture.service.SpaceService;
import com.qing.picture.service.SpaceUserService;
import com.qing.picture.service.UserService;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 86157
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-03-19 16:39:47
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceService{

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private SpaceUserService spaceUserService;

    @Resource
    @Lazy
    private DynamicShardingManager dynamicShardingManager;


    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        SpaceLevelEnum level = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (level != null) {
            Long maxSize = level.getMaxSize();
            if(space.getMaxSize() == null){
                space.setMaxSize(maxSize);     //设置最大容量
            }
            Long maxCount = space.getMaxCount();
            if(maxCount == null){
                space.setMaxCount(level.getMaxCount());     //设置最大数量
            }
        }
    }

    @Override
    public Long addUserSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        this.fillSpaceBySpaceLevel(space);

        //设置默认空间
        if(space.getSpaceLevel() == null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (spaceAddRequest.getSpaceType() == null) {
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        if(space.getSpaceName() == null){
            space.setSpaceName("默认空间");
        }
        if(space.getUserId() == null){
            space.setUserId(loginUser.getId());
        }

        space.setCreateTime(new Date());
        space.setUpdateTime(new Date());
        space.setEditTime(new Date());

        //校验权限
        if(!space.getSpaceLevel().equals(SpaceLevelEnum.COMMON.getValue()) && !userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"权限不足，无法指定空间等级");
        }
        Integer spaceType = space.getSpaceType();
        ThrowUtils.throwIf(spaceType==null,ErrorCode.OPERATION_ERROR,"空间类型不能为空");


        // 使用redisson分布式锁
        String lockKey = "lock-space-"+loginUser.getId();
        RReadWriteLock lock = redissonClient.getReadWriteLock(lockKey);
        RLock wLock = lock.writeLock();
        try{
            wLock.lock();
            //设置空间所属用户
            Long newSpaceId = transactionTemplate.execute(status -> {
                boolean  existsSpace = this.lambdaQuery().eq(Space::getUserId, loginUser.getId()).eq(Space::getSpaceType, spaceAddRequest.getSpaceType()).exists();
                ThrowUtils.throwIf(existsSpace, ErrorCode.OPERATION_ERROR,"每个用户每类空间仅能创建一个");

                boolean res =this.save(space);
                ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR,"创建空间失败");
                // 如果是团队空间，关联新增团队成员记录
                if (SpaceTypeEnum.TEAM.getValue() == spaceAddRequest.getSpaceType()) {
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(loginUser.getId());
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    res = spaceUserService.save(spaceUser);
                    ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                }
                // 创建分表
//                dynamicShardingManager.createSpacePictureTable(space);
                // 返回新写入的数据 id
                return space.getId();
            });
            return Optional.ofNullable(newSpaceId).orElse(-1L);
        }finally {
            wLock.unlock();
        }
    }

    @Override
    public boolean updateUserSpace(SpaceUpdateRequest updateRequest, User loginUser) {
        Space space = this.getById(updateRequest.getId());
        ThrowUtils.throwIf(space == null, ErrorCode.OPERATION_ERROR,"空间不存在");
        //校验权限
        ThrowUtils.throwIf(!userService.isAdmin(loginUser) && !space.getUserId().equals(loginUser.getId()),ErrorCode.OPERATION_ERROR,"权限不足，无法修改该空间");
        Integer spaceType = space.getSpaceType();
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(spaceType);
        ThrowUtils.throwIf(spaceTypeEnum==null||spaceType==null,ErrorCode.OPERATION_ERROR,"修改空间类型不能为空");

        Space updateSpace = new Space();
        BeanUtils.copyProperties(updateRequest, updateSpace);
        this.fillSpaceBySpaceLevel(updateSpace);

        return this.updateById(updateSpace);
    }


    /**
     * 用于用户编辑空间信息
     * @param editRequest
     * @param user
     * @return
     */
    @Override
    public boolean editUserSpace(SpaceEditRequest editRequest, User user) {
        Space space = this.getById(editRequest.getId());
        ThrowUtils.throwIf(space == null, ErrorCode.OPERATION_ERROR,"空间不存在");
        //校验权限
        ThrowUtils.throwIf(!space.getUserId().equals(user.getId()),ErrorCode.OPERATION_ERROR,"权限不足，无法修改该空间");
        Space updateSpace = new Space();
        BeanUtils.copyProperties(editRequest, updateSpace);
        return this.updateById(updateSpace);
    }

    @Override
    public SpaceVo getSpaceVo(Space space, HttpServletRequest request) {
        SpaceVo spaceVo = SpaceVo.objToVo(space);
        // 关联查询用户信息
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVo userVO = userService.getUserVO(user);
            spaceVo.setUserVo(userVO);
        }
        return spaceVo;
    }

    @Override
    public Page<SpaceVo> getSpaceVoPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVo> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVo> spaceVOList = spaceList.stream()
                .map(SpaceVo::objToVo)
                .collect(Collectors.toList());
        // 1. 关联查询用户信息
        // 1,2,3,4
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        // 1 => user1, 2 => user2
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUserVo(userService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }


    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        // 拼接查询条件
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

}




